package work.juzheng;

public class Problem48 {
    public void rotate(int[][] matrix) {

        int n = matrix.length;
        int[] ans = new int[n * n];
        int time = 0, x = 0;
        while (time <= n / 2) {
            for (int i = n - time - 1; i > time; i--) {
                ans[x++] = matrix[i][time];
            }
            for (int i = time; i < n - time - 1; i++) {
                ans[x++] = matrix[time][i];
            }
            for (int i = time; i < n - time - 1; i++) {
                ans[x++] = matrix[i][n - time - 1];
            }
            for (int i = n - time - 1; i > time; i--) {
                ans[x++] = matrix[n - time - 1][i];
            }
            time++;
        }

        x = time = 0;
        while (time <= n / 2) {
            for (int i = time; i < n - time - 1; i++) {
                matrix[time][i] = ans[x++];
            }
            for (int i = time; i < n - time - 1; i++) {
                matrix[i][n - time - 1] = ans[x++];
            }
            for (int i = n - time - 1; i > time; i--) {
                matrix[n - time - 1][i] = ans[x++];
            }
            for (int i = n - time - 1; i > time; i--) {
                matrix[i][time] = ans[x++];
            }
            time++;
        }
    }


    public static void main(String[] args) {
        Problem48 problem48 = new Problem48();
        int[][] nums = new int[][]{{5, 1, 9, 11}, {2, 4, 8, 10}, {13, 3, 6, 7}, {15, 14, 12, 16}};
        problem48.rotate(nums);
    }
}
